package com.uuah.server.config.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.SmartFactoryBean;

import com.uuah.config.i18n.MessageFactory;
import com.uuah.server.api.IUuahContext;
import com.uuah.server.api.config.IUuahConfiguration;
import com.uuah.server.api.context.IUuahContextAware;
import com.uuah.server.config.UuahConfiguration;
import com.uuah.server.exception.config.ConfigurationException;

/**
 * This class is a "SmartFactoryBean" which allows a few XML attributes to be
 * set on the otherwise read-only UuahConfiguration. It looks up the
 * UuahConfiguration from the UuahContext and does some class-casting to be able
 * to modify it. Note that this will only work if the UuahContext has not yet
 * been started, otherwise the modifications will be ignored (and warnings
 * logged).
 *
 * <p>
 * update record:updator，update time，update content and version
 * </p>
 *
 * @author <a href="jonny_quan@hotmail.com">jonny</a>
 * @date 2009 2009-3-27 下午01:25:03
 * @version 1.0.0
 */
public class UuahConfigurationConfigurator implements IUuahContextAware,
		SmartFactoryBean {
	private IUuahContext uuahContext;

	private UuahConfiguration config = new UuahConfiguration();

	protected transient Logger logger = LoggerFactory
			.getLogger(UuahConfigurationConfigurator.class);

	public void setUuahContext(IUuahContext context) {
		this.uuahContext = context;
	}

	public boolean isEagerInit() {
		return true;
	}

	public boolean isPrototype() {
		return false;
	}

	public Object getObject() throws Exception {
		IUuahConfiguration configuration = uuahContext.getConfiguration();
		if (configuration instanceof UuahConfiguration) {
			((UuahConfiguration) configuration)
					.setDefaultSynchronousEndpoints(config
							.isDefaultSynchronousEndpoints());
			((UuahConfiguration) configuration)
					.setDefaultSynchronousEventTimeout(config
							.getDefaultSynchronousEventTimeout());
			return configuration;
		} else {
			throw new ConfigurationException(
					MessageFactory
							.createStaticMessage("Unable to set properties on read-only UuahConfiguration: "
									+ configuration.getClass()));
		}
	}

	public Class getObjectType() {
		return IUuahConfiguration.class;
	}

	public boolean isSingleton() {
		return true;
	}

	public void setDefaultSynchronousEndpoints(boolean synchronous) {
		config.setDefaultSynchronousEndpoints(synchronous);
	}

	public void setDefaultSynchronousEventTimeout(int synchronousEventTimeout) {
		config.setDefaultSynchronousEventTimeout(synchronousEventTimeout);
	}
}
